<?php
/**
 * Created by Sublime.
 * Author: lingyun
 * Date: 2017-12-07 15:29:32
 * @desc 微信支付配置
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Model;
use Wechat\Lib\Tools;

use app\comm\controller\PcLogController;
use app\comm\service\WeixinpayService;
use Endroid\QrCode\QrCode;
use \think\Loader;

class Weixinpay extends PcLogController{
	/**
	 * 微信支付生成二维码图片
	 * @Author   lingyun
	 * @DateTime 2017-12-07T15:32:19+0800
	 * @return   [type]                   [description]
	 */
	public function create_paycode($parm){
		$post = input('param.');
		halt($post);
		if(empty($post['order_sn'])){
			$this->error('缺少订单号',url('Index/index'));
		}
		//$post["openid"] =session("openid");
		$service = new WeixinpayService();		//实例化微信支付类
		$pay_code = $service->_pay_payqrc($post);	//支付二维码
		$result = json_decode($pay_code,true);
		if($result['code'] == 0){
			halt($result['msg']);
		}else{
			halt($result['url']);
		}
		// halt($result);
	}


	/**
	 * 微信支付
	 * @Author   lingyun
	 * @DateTime 2017-12-07T16:50:27+0800
	 * @return   [type]                   [description]
	 */
	public function weixin_pay(){
		$post = input('param.');

		$result = $this->order_sn_check($post);
		if($result["status"]==0){
			$this->error($result["data"]);
		}
		$out_trade_no = $post['order_sn'];
		$total_fee    =  $post['final_amount']*100;
		$total_fee = 1;
		//微信浏览器端
		$pay          = 	& load_wechat('Pay');
		if(!empty(session("openid"))){
			$pay          = & load_wechat('Pay');
			$openid       =  session("openid");
			$notify_url   = "http://ysbl.fxshe.com".url("@index/notify/notifyweixinpay");
			$body         ="微信支付";
				
			$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no,$total_fee,$notify_url, $trade_type = "JSAPI");
			//更新预支付
			$prepaydata= ["prepayid"=>$prepayid];
			Db::table("ys_order")->where("order_sn",$out_trade_no)->update($prepaydata);

			$options = $pay->createMchPay($prepayid);
			$this->assign('options',json_encode($options));
			return view("weixinpay/weixin_pay");
		}
	   
		$body         ="微信扫码支付";
		$notify_url   = "http://ysbl.fxshe.com".url("@index/notify/notifyweixinpay");
        $prepayid 	  =$pay->getPrepayId(null, $body, $out_trade_no,$total_fee,$notify_url, $trade_type = "NATIVE");
   		//更新预支付
   		$prepaydata= ["prepayid"=>$prepayid];
		Db::table("ys_order")->where("order_sn",$out_trade_no)->update($prepaydata);
   		$this->assign('prepayid',$prepayid);
   		$this->assign('out_trade_no',$out_trade_no);
   		return view("weixinpay/weixinerwei");
        exit;
	

	}

	//业务检查
	public function order_sn_check($post){
		$order = Db::table("ys_order")->where("order_sn",$post['order_sn'])->find();
		if(empty($order)){
			return ["status"=>0,"data"=>'没有该订单'];
		}
		if($order["order_status"]!=0){
			return ["status"=>0,"data"=>'该订单,已经支付过'];
		}
		if(time()-3600>$order["addtime"]){
			return ["status"=>0,"data"=>'该订单已过期'];
		}
		return ["status"=>1,"data"=>'可以支付'];
	}

	//ajax 轮询地址
	public function order_sn_ajax(){
		$order_sn = request()->get("out_trade_no");
		$order = Db::table("ys_order")->where("order_sn",$order_sn)->find();
		if($order["order_status"]!=0){
			return ["status"=>1,"data"=>'支付完成'];
		}else{
			return ["status"=>0,"data"=>'没有支付'];
		}

	}

	/**
	 * 向支付平台查询订单状态
	 * @Author   lingyun
	 * @DateTime 2017-12-08T15:02:42+0800
	 * @return   [type]                   [description]
	 */
	public function check_order($order_sn){
		$service = new WeixinpayService();		//实例化微信支付类
		halt($service->checkorderstatus($order_sn));
	}

	//微信支付
	public function weixinzhifu(){
		$script = &  load_wechat('Script');
		$url = $this->request->url(true);
		$config = $script->getJsSign($url);
		$config["debug"] = true;
		$this->assign('config',json_encode($config));

		$post = input('param.');
		$pay = & load_wechat('Pay');
		$openid=session("openid");
		$body  = "微信支付";
		$out_trade_no =time().rand(1000,900000);
		$total_fee   = 1;
		$notify_url= "http://ysbl.fxshe.com".url("@index/notify/notifyweixinpay");
		$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
		$options = $pay->createMchPay($prepayid);
		unset($options["timestamp"]);
		$this->assign('options',json_encode($options));
		return view("weixinpay/weixinzhifu");
		//$qrc = $pay->getQrcPayUrl($post["order_sn"]);
	}

    /**
     * @Author lignyun
     * @Desc 会员充值
     */
    public function recharge()
    {
        $post = input('param.');
        $post['final_amount'] = $post['amount'];
        $data = array(
            'uid'=>$post['uid'],
            'admin_id'=>0,
            'store_id'=>0,
            'order_id'=>0,
            'order_sn'=>$post['order_sn'],
            'pay_status'=>0,
            'pay_type'=>$post['pay_type'],
            'amount'=>$post['amount'],
            'sign'=>2,
            'chargetype'=>1,
            'charge_cn'=>"会员充值",
            'addtime'=>time()
        );
        Db::name('user_wallet_log')->insert($data);
        $result = $this->check_recharge_order($post);        //检查订单状态
        if ($result["status"] == 0) {
            $this->error($result["msg"]);
        }
        $out_trade_no = $post['order_sn'];
        $total_fee = $post['final_amount'] * 100;
        $total_fee = 1;
        //微信浏览器端
        $pay = 	&load_wechat('Pay');
        if (!empty(session("openid"))) {
            $pay = &load_wechat('Pay');
            $openid = session("openid");
            $notify_url = "http://ysbl.fxshe.com" . url("@index/notify/wx_notifyrecharge");
            $body = "微信支付";

            $prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
            //更新预支付
            $prepaydata = ["prepayid" => $prepayid];
            Db::table("ys_order")->where("order_sn", $out_trade_no)->update($prepaydata);

            $options = $pay->createMchPay($prepayid);
            $this->assign('options', json_encode($options));
            return view("weixinpay/weixin_pay");
        }
    }

    /**
     * @Author lignyun
     * @Desc    会员充值 -- 二维码
     */
    public function recharge_code(){
        $post = input('param.');
        $post['final_amount'] = $post['amount'];
        $data = array(
            'uid'=>$post['uid'],
            'admin_id'=>0,
            'store_id'=>0,
            'order_id'=>0,
            'order_sn'=>$post['order_sn'],
            'pay_status'=>0,
            'pay_type'=>$post['pay_type'],
            'amount'=>$post['amount'],
            'sign'=>2,
            'chargetype'=>1,
            'charge_cn'=>"会员充值",
            'addtime'=>time()
        );
        Db::name('user_wallet_log')->insert($data);
        $pay          = 	& load_wechat('Pay');
        $body         ="微信扫码支付";
        $total_fee = 1;
        $notify_url   = "http://ysbl.fxshe.com".url("@index/notify/notifyweixinpay_code");
        $prepayid 	  =$pay->getPrepayId(null, $body, $post['order_sn'],$total_fee,$notify_url,     $trade_type = "NATIVE");
        //更新预支付
        $prepaydata= ["prepayid"=>$prepayid];
        Db::table("ys_order")->where("order_sn",$post['order_sn'])->update($prepaydata);
        $this->assign('prepayid',$prepayid);
        $this->assign('out_trade_no',$post['order_sn']);
        return view("weixinpay/weixinerwei");
        exit;
    }

    /**
     * @Author lignyun
     * @Desc    检查充值订单
     */
    private function check_recharge_order($post){
        if(empty($post['order_sn'])){
            return ['status'=>0,'msg'=>'找不到支付订单,请重新充值'];
        }else{
            $order = Db::name('user_wallet_log')->where("order_sn",$post['order_sn'])->find();
            if(empty($order)){
                return ['status'=>0,'msg'=>'找不到支付信息,请重新再试'];
            }else if($order['pay_status'] == 1){
                return ['status'=>0,'msg'=>'该订单已支付，请勿重复支付'];
            }else if(time()-3600>$order["addtime"]){
                return ['status'=>0,'msg'=>'该订单已过期，不能进行支付'];
            }
        }
        return ['status'=>1,'msg'=>'找到订单'];
    }

}